package com.zhw.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zhw.Util.JwtUtils;
import com.zhw.mapper.BookMapper;
import com.zhw.mapper.RecordMapper;
import com.zhw.pojo.*;
import com.zhw.pojo.Record;
import com.zhw.service.RecordService;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;

@Service
public class RecordServiceImpl implements RecordService {
    @Autowired
    BookMapper bookMapper;

    @Autowired
    RecordMapper recordMapper;

    @Autowired
    HttpServletRequest request;




    @Transactional
    @Override
    public void borrow(String isbn) {
        Book book = bookMapper.getByID(isbn);
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        String username = (String) claims.get("username");
        Record r=new Record();
        r.setName(book.getName());
        r.setBorrower(username);
        r.setISBN(isbn);
        r.setStatus(0);
        r.setBorrow_time(LocalDate.now());
        r.setDeadline(LocalDate.now().plusDays(7));
        recordMapper.save(r);
        book.setStorage(book.getStorage()- 1);
        bookMapper.update(book);
    }

    @Override
    public PageBean page(RecordDTO recordDTO) {
        PageHelper.startPage(recordDTO.getPage(),recordDTO.getPageSize());
        Page<RecordVO> result=recordMapper.page(recordDTO);
        return new PageBean(result.getTotal(),result.getResult());
    }

    @Transactional
    @Override
    public void give(String isbn) {
        Book book = bookMapper.getByID(isbn);
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        String username = (String) claims.get("username");
        Record r=new Record();
        r.setISBN(isbn);
        r.setStatus(1);
        r.setReturnTime(LocalDate.now());
        r.setBorrower(username);
        int row = recordMapper.update(r);
        System.out.println("更新行数"+row);
        book.setStorage(book.getStorage()+row);
        bookMapper.update(book);
    }
}
